package index;

import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class FirstIndex {

	public static void main(String[] args) throws Exception {
		
		String indexDir = "/Users/apple/lucene/index";
		String dataDir = "/Users/apple/lucene/data";
		
		long start = System.currentTimeMillis();
		FirstIndex indexer = new FirstIndex(indexDir);
		int numberIndex = indexer.index(dataDir, new TextFilesFilter());
		indexer.close();
		long end = System.currentTimeMillis();
		System.out.println("搜索到：" + numberIndex + "个文件夹，共花费：" + (end - start) + "毫秒");
	}
	
	private IndexWriter writer;
	
	public FirstIndex(String indexDir) throws IOException{
		
		Directory dir = FSDirectory.open(new File(indexDir));
//		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_42);
		writer = new IndexWriter(dir, new StandardAnalyzer(Version.LUCENE_33), true,
				IndexWriter.MaxFieldLength.UNLIMITED);
	}
	
	public void close() throws Exception{
		
		writer.close();
	}
	
	public int index(String dataDir, FileFilter filter) throws Exception{
		
		File[] files = new File(dataDir).listFiles();
		for(File f :files){
			
			if(!f.isDirectory() && !f.isHidden() && f.exists() && f.canRead() && (filter == null || filter.accept(f))) {
				
				System.out.println("Indexing " + f.getCanonicalPath());
				Document doc = new Document();
				doc.add(new Field("文档", new FileReader(f)));
				doc.add(new Field("文件名", f.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED));
				doc.add(new Field("路径", f.getCanonicalPath(), Field.Store.YES, Field.Index.NOT_ANALYZED));
				writer.addDocument(doc);
			}
		}
		return writer.numDocs();
	}
	
	public static class TextFilesFilter implements FileFilter{
		
		private String[] array = new String[]{".txt", ".doc", ".docx"};
		
		public boolean accept(File path){
			
			for(int i = 0; i < array.length; i++){

				if(path.getName().toLowerCase().endsWith(array[i])){
					
					return true;
				}
			}
			return false;
		}
	}
}
